package com.ylr.demo2.JsonView;

import com.fasterxml.jackson.annotation.JsonView;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author 11
 * @Date 2021/6/19 15:05
 * @Version 1.0
 */

@RestController
@Slf4j
public class UserController {

    private static final String ENCODING = "GBK";


    @GetMapping("/user")
    @JsonView({User.FieldSimpleView.class})
    public List<User> query() {
        List<User> users = new ArrayList<>();
        users.add(new User(1, "john", "123456",5));
        users.add(new User(2, "tom", "123456",6));
        users.add(new User(3, "jim", "123456",7));
        return users;
    }

    /**
     * 在url中使用正则表达式
     *
     * @param id
     * @return
     */
    @GetMapping("/user/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User get(@PathVariable String id) {
        User user = new User(1, "john", "123456",8);
//        user.setUsername("tom");
        return user;
    }

    @RequestMapping(value ="/notify", produces ="application/xml;charset=GBK")
    @ResponseBody
    //只能返回string?
    public String notify(int orderNo, HttpServletRequest request) {
        User user = new User(orderNo, "john", "123456",8);
        String ctype = request.getContentType();
        log.info(">>>>  {}",ctype);
        return user.toString();
    }

    @RequestMapping(value ="/notify1")
    @ResponseBody
    public void notify1(int orderNo, HttpServletRequest request,HttpServletResponse response) {
        User user = new User(orderNo, "john", "123456",8);
        String ctype = request.getContentType();
        log.info(">>>>  {}",ctype);
        try {
            response.setContentType("application/xml;charset=GBK");
            ServletOutputStream output = response.getOutputStream();
            String resBody =  user.toString();
            log.info("<<<返回结果为：{}", resBody);
            IOUtils.write(resBody, output, ENCODING);
            output.close();
        } catch (IOException e) {
            log.error("输出响应报文异常", e);
        }
        return;
    }
}
